export const toArr = (treeData: any, { children = 'children' } = {}) => {
  const result: any = [];
  treeData.forEach((item: any) => {
    traverse(item);
  });
  function traverse(item: any) {
    result.push(item);
    if (item[children]) {
      item[children].forEach((child: any) => {
        traverse(child);
      });
    }
  }
  return result;
};

export const filter = (
  treeData: any,
  callback: ({ node, parentNode }: any) => boolean,
  { children = 'children' } = {}
) => {
  const handleNode = (node: any, parentNode: any) => {
    if (callback({ node, parentNode })) {
      if (node[children]) {
        node[children] = node[children].filter((child: any) => {
          return handleNode(child, node);
        });
      }
    }
    return node;
  };
  const copyTreeData = JSON.parse(JSON.stringify(treeData));
  return copyTreeData
    .filter((node: any) => {
      return callback({ node, parentNode: null });
    })
    .map((v: any) => {
      return handleNode(v, null) ? v : null;
    });
};

export const addTreeKey = (treeData: any[], key: string, defaultVal?: any) => {
  const data = JSON.parse(JSON.stringify(treeData));
  addTreeKeyEach(data, key, defaultVal);
  return data;
  // const handleNode = (node: any, parentNode: any) => {
  //   if (callback({ node, parentNode })) {
  //     if (node[children]) {
  //       node[children] = node[children].filter((child: any) => {
  //         return handleNode(child, node);
  //       });
  //     }
  //   }
  // };
};
function addTreeKeyEach(list: any[], key: string, defaultVal?: any) {
  list.forEach((item: any) => {
    if (key) {
      item[key] = defaultVal;
    }
    if (item.children && item.children.length > 0) {
      addTreeKeyEach(item.children, key, defaultVal);
    }
  });
}
